package com.kaixinff.kaixin001.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.kaixinff.kaixin001.util.Filter;
import com.kaixinff.kaixin001.util.KXClient;
import com.kaixinff.kaixin001.util.KXUtil;
import com.kaixinff.kaixin001.util.RegStep;
import com.kaixinff.name.User;
import com.kaixinff.net.NameValuePair;

@SuppressWarnings("serial")
public class XWHelpServlet extends HttpServlet {
	private static final String INDEX_URL = KXUtil.XW_URL + "/index.php";
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html; charset=" + KXUtil.CHARSET);
		List<User> users = KXUtil.getUsers(new Filter(){
			@Override
			public boolean access(User user) {
				return user.hasStep(RegStep.ADD_XW);
			}}, resp);
		if (users == null) {
			return;
		}
		
		for (User user : users) {
			try {
				heplShow(KXClient.getInstance(user.getId()));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void heplShow(KXClient client) throws IOException, JSONException {
		String cont = client.doGet(INDEX_URL, null).getContent();
		int cid = getCid(cont);
		if (cont.indexOf("XW.Help.show();") > -1) {
			String url = KXUtil.XW_URL + "/!ajax_help.php?flag=show&cid=" + cid + "&tmp=" + Math.random() + "&rt=json";
			String json = client.doGet(url, null).getContent();
			JSONObject jobj = new JSONObject(json);
			if ("suc".equals(jobj.getString("flag")) && jobj.has("title") && jobj.has("content")) {
				System.out.println(jobj.getString("title") + ": " + KXUtil.findMessage(jobj.getString("content")));
				
				url = KXUtil.XW_URL + "/!ajax_help.php?flag=request&cid=" + cid + "&tmp=" + Math.random() + "&rt=json";
				json = client.doGet(url, null).getContent();
				jobj = new JSONObject(json);
				String hkey = jobj.getString("hkey");
				String feedt = jobj.getString("feedt");
				                        
				url = KXUtil.XW_URL + "/!ajax_sysfeed.php?hkey=" + hkey + "&feedt=" + feedt + "&flag=friendhelp&cid=" + cid + "&tmp=" + Math.random() + "&rt=json";
				json = client.doGet(url, null).getContent();
				jobj = new JSONObject(json);
				String encode = jobj.getString("encode");
				
				url = KXUtil.HOST_URL + "/interface/inner_sendnews_dialog.php?para=" + encode + "&type=1&mode=0&r=" + Math.random();
				String html = client.doGet(url, null).getContent();
				String uid = null;
				Pattern p = Pattern.compile("&fromuid=(\\d+?)&");
				Matcher m = p.matcher(html);
				if (m.find()) {
					uid = m.group(1);
				}
				
				url = KXUtil.HOST_URL  + "/interface/aj_inner_sendnews_dialog.php";
				client.doPost(url, null, new NameValuePair[]{new NameValuePair("para", encode), 
						new NameValuePair("type", "1"), new NameValuePair("content", "x")}).getContent();
				
				requireHelp(client, uid, hkey, feedt, cid);
			} else {
				System.err.println(json + ": " + url);
			}
		} else if (cont.indexOf("XW.Help.msgHelp(XW.Help.msg);") > -1) {
			Pattern p = Pattern.compile("fromuid=(\\d+?)&hkey=(.+?)&feedt=(\\d+?)");
			Matcher m = p.matcher(cont);
			if (m.find()) {
				String uid = m.group(1);
				String hkey = m.group(2);
				String feedt = m.group(3);
				requireHelp(client, uid, hkey, feedt, cid);
			}
		}
	}
	
	private int getCid(String html) {
		Pattern p = Pattern.compile("\"cid\"[:]\"(\\d+?)\"");
		Matcher m = p.matcher(html);
		if (m.find()) {
			return Integer.parseInt(m.group(1));
		}
		return 2;		
	}
	
	private void requireHelp(KXClient client, String uid, String hkey, String feedt, int cid) throws IOException, JSONException {
		List<String> friends = getFriends(client);
		Properties properties = KXUtil.getUid2Email();
		for (String friend : friends) {
			if (properties.containsKey(friend)) {
				KXClient c = KXClient.getInstance((String) properties.get(friend));
				boolean reuslt = help(c, uid, hkey, feedt);
				if (reuslt) {
					String cont = client.doGet(INDEX_URL, null).getContent();
					Pattern p = Pattern.compile("XW[.]Help[.]getHelp[(]'(.+?)'[)];");
					Matcher m = p.matcher(cont);
					if (m.find()) {
						String url = KXUtil.XW_URL + "/!ajax_help.php?hkey=" + m.group(1) + "&flag=gethelp&cid=" + cid + "&tmp=" + Math.random() + "&rt=json";
						String json = client.doGet(url, INDEX_URL).getContent();
						JSONObject jobj = new JSONObject(json);
						System.out.println(KXUtil.findMessage(jobj.getString("content")));
					} else {
						System.err.println(cont);
					}
					break;
				}
			}
		}
	}
	
	private List<String> getFriends(KXClient client) throws IOException {
		List<String> uids = new ArrayList<String>();
		String url = KXUtil.HOST_URL + "/friend/editorder.php";
		String html = client.doGet(url, null).getContent();
		Pattern p = Pattern.compile("\"uid\":\"(\\d+?)\",");
		Matcher m = p.matcher(html);
		while (m.find()) {
			String uid = m.group(1);
			uids.add(uid);
		}
		return uids;
	}
	
	private boolean help(KXClient c, String uid, String hkey, String feedt) throws IOException, JSONException {
		String cont = c.doGet(INDEX_URL, null).getContent();
		int cid = getCid(cont);
		String url = KXUtil.XW_URL + "/!ajax_help.php?flag=dohelp&uid=" + uid + "&hkey=" + hkey + "&cid=" + cid + "&tmp=" + Math.random() + "&rt=json";
		String json = c.doGet(url, null).getContent();
		JSONObject jobj = new JSONObject(json);
		System.out.println(KXUtil.findMessage(jobj.getString("content")));
		return jobj.getString("content").indexOf("\u5b8c\u6210\u8fd9\u4e2a\u4efb\u52a1\u4e86") > -1;
	}
}
